package com.bf.electroplating.service.impl;

import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bf.electroplating.login.UserContext;
import com.bf.electroplating.login.UserDetail;
import com.bf.electroplating.mapper.CameraMonitoringMapper;
import com.bf.electroplating.pojo.entity.CameraMonitoring;
import com.bf.electroplating.pojo.entity.ComCompany;
import com.bf.electroplating.pojo.vo.ResultVO;
import com.bf.electroplating.pojo.vo.cameraMonitoringVO.CameraMonitoringAddDTO;
import com.bf.electroplating.pojo.vo.cameraMonitoringVO.CameraMonitoringDetailDTO;
import com.bf.electroplating.pojo.vo.cameraMonitoringVO.CameraMonitoringQueryDTO;
import com.bf.electroplating.pojo.vo.cameraMonitoringVO.CameraMonitoringUpdateDTO;
import com.bf.electroplating.pojo.vo.cameraMonitoringVO.CameraMonitoringVO;
import com.bf.electroplating.service.ComCompanyService;
import com.bf.electroplating.service.ICameraMonitoringService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 监控摄像机表 服务实现类
 * </p>
 *
 * @author gzd
 * @since 2025-11-19
 */
@Service
public class CameraMonitoringServiceImpl extends ServiceImpl<CameraMonitoringMapper, CameraMonitoring> implements ICameraMonitoringService {

    @Resource
    private ComCompanyService comCompanyService;
    @Override
    public ResultVO<Page<CameraMonitoringVO>> pageList(CameraMonitoringQueryDTO queryDTO) {
        Page<CameraMonitoring> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());

        LambdaQueryWrapper<CameraMonitoring> wrapper = new LambdaQueryWrapper<>();

        if (org.apache.commons.lang3.StringUtils.isNotBlank(queryDTO.getCompanyId())) {
            wrapper.eq(CameraMonitoring::getCompanyId, queryDTO.getCompanyId());
        }

        if (StringUtils.isNotBlank(queryDTO.getCameraName())) {
            wrapper.like(CameraMonitoring::getCameraName, queryDTO.getCameraName());
        }

        if (StringUtils.isNotBlank(queryDTO.getDeviceCode())) {
            wrapper.like(CameraMonitoring::getDeviceCode, queryDTO.getDeviceCode());
        }

        if (StringUtils.isNotBlank(queryDTO.getDeviceStatus())) {
            wrapper.eq(CameraMonitoring::getDeviceStatus, queryDTO.getDeviceStatus());
        }

        wrapper.eq(CameraMonitoring::getDelFlag, "0");
        wrapper.orderByDesc(CameraMonitoring::getCreateTime);

        Page<CameraMonitoring> resultPage = this.page(page, wrapper);

        // 转换为VO
        Page<CameraMonitoringVO> voPage = new Page<>();
        BeanUtils.copyProperties(resultPage, voPage, "records");
        List<CameraMonitoringVO> voList = new ArrayList<>();
        for (CameraMonitoring entity : resultPage.getRecords()) {
            CameraMonitoringVO vo = new CameraMonitoringVO();
            BeanUtils.copyProperties(entity, vo);
            if (entity.getCreateTime() != null) {
                vo.setCreateTime(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(entity.getCreateTime()));
            }
            if (entity.getUpdateTime() != null) {
                vo.setUpdateTime(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(entity.getUpdateTime()));
            }
            // 设备状态描述
            if ("1".equals(entity.getDeviceStatus())) {
                vo.setDeviceStatusDesc("在线");
            } else if ("0".equals(entity.getDeviceStatus())) {
                vo.setDeviceStatusDesc("离线");
            }
            voList.add(vo);
        }
        voPage.setRecords(voList);
        return ResultVO.ok(voPage);
    }

    @Override
    public ResultVO<CameraMonitoringVO> getDetail(CameraMonitoringDetailDTO dto) {
        if (StringUtils.isBlank(dto.getCameraId())) {
            return ResultVO.fail("摄像头ID不能为空");
        }
        CameraMonitoring entity = this.getOne(new LambdaQueryWrapper<CameraMonitoring>().eq(CameraMonitoring::getCameraId,dto.getCameraId()),false);
        if (entity == null || "1".equals(entity.getDelFlag())) {
            return ResultVO.fail("记录不存在");
        }
        CameraMonitoringVO vo = new CameraMonitoringVO();
        BeanUtils.copyProperties(entity, vo);
        if (entity.getCreateTime() != null) {
            vo.setCreateTime(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(entity.getCreateTime()));
        }
        if (entity.getUpdateTime() != null) {
            vo.setUpdateTime(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").format(entity.getUpdateTime()));
        }
        // 设备状态描述
        if ("1".equals(entity.getDeviceStatus())) {
            vo.setDeviceStatusDesc("在线");
        } else if ("0".equals(entity.getDeviceStatus())) {
            vo.setDeviceStatusDesc("离线");
        }
        return ResultVO.ok(vo);
    }

    @Override
    public ResultVO<String> save(CameraMonitoringAddDTO dto) {
        try {
            UserDetail currentUser = UserContext.getUser();
            if (currentUser == null) {
                return ResultVO.fail("用户未登录");
            }

            CameraMonitoring entity = new CameraMonitoring();
            BeanUtils.copyProperties(dto, entity);

            // 设置基础信息
            entity.setCameraId(UUID.randomUUID().toString().replaceAll("-", ""));
            entity.setParkId(currentUser.getParkId());
            if (org.apache.commons.lang3.StringUtils.isBlank(entity.getCompanyId())) {
                entity.setCompanyId(currentUser.getCompanyId());
            }
            entity.setCreateBy(currentUser.getId());
            entity.setCreateTime(LocalDateTime.now());
            entity.setDelFlag("0");
            ComCompany comCompany =comCompanyService.getById(dto.getCompanyId());
            entity.setCompanyAbbreviation(comCompany.getCompanyAbbreviation());

            if (org.apache.commons.lang3.StringUtils.isBlank(entity.getDeviceStatus())) {
                entity.setDeviceStatus("0"); // 默认离线
            }

            boolean result = this.save(entity);
            if (result) {
                return ResultVO.ok("新增成功");
            } else {
                return ResultVO.fail("新增失败");
            }
        } catch (Exception e) {
            return ResultVO.fail("新增失败：" + e.getMessage());
        }
    }

    @Override
    public ResultVO<String> update(CameraMonitoringUpdateDTO dto) {
        try {
            UserDetail currentUser = UserContext.getUser();
            if (currentUser == null) {
                return ResultVO.fail("用户未登录");
            }

            if (StringUtils.isBlank(dto.getCameraId())) {
                return ResultVO.fail("摄像头ID不能为空");
            }

            // 验证数据是否存在
            CameraMonitoring existing = this.getOne(new LambdaQueryWrapper<CameraMonitoring>().eq(CameraMonitoring::getCameraId,dto.getCameraId()),false);
            if (existing == null || "1".equals(existing.getDelFlag())) {
                return ResultVO.fail("数据不存在");
            }

            // 验证企业权限（如果用户有企业ID限制）
//            if (org.apache.commons.lang3.StringUtils.isNotBlank(currentUser.getCompanyId())
//                    && org.apache.commons.lang3.StringUtils.isNotBlank(existing.getCompanyId())
//                    && !currentUser.getCompanyId().equals(existing.getCompanyId())) {
//                // 如果用户有园区权限，则允许操作
//                if (CollectionUtils.isEmpty(currentUser.getParkFunctionIds())) {
//                    return ResultVO.fail("无权限操作此数据");
//                }
//            }

            // 设置更新信息
            BeanUtils.copyProperties(dto, existing);
            existing.setUpdateBy(currentUser.getId());
            existing.setUpdateTime(LocalDateTime.now());

            boolean result = this.updateById(existing);
            if (result) {
                return ResultVO.ok("修改成功");
            } else {
                return ResultVO.fail("修改失败");
            }
        } catch (Exception e) {
            return ResultVO.fail("修改失败：" + e.getMessage());
        }
    }

    @Override
    public ResultVO<String> delete(String cameraId) {
        try {
            UserDetail currentUser = UserContext.getUser();
            if (currentUser == null) {
                return ResultVO.fail("用户未登录");
            }

            if (StringUtils.isBlank(cameraId)) {
                return ResultVO.fail("摄像头ID不能为空");
            }

            CameraMonitoring existing = this.getOne(new LambdaQueryWrapper<CameraMonitoring>().eq(CameraMonitoring::getCameraId,cameraId),false);
            if (existing == null || "1".equals(existing.getDelFlag())) {
                return ResultVO.fail("数据不存在");
            }

            // 验证企业权限
            if (org.apache.commons.lang3.StringUtils.isNotBlank(currentUser.getCompanyId()) 
                    && org.apache.commons.lang3.StringUtils.isNotBlank(existing.getCompanyId())
                    && !currentUser.getCompanyId().equals(existing.getCompanyId())) {
                if (CollectionUtils.isEmpty(currentUser.getParkFunctionIds())) {
                    return ResultVO.fail("无权限操作此数据");
                }
            }

            // 逻辑删除
            existing.setDelFlag("1");
            existing.setUpdateBy(currentUser.getId());
            existing.setUpdateTime(LocalDateTime.now());

            boolean result = this.updateById(existing);
            if (result) {
                return ResultVO.ok("删除成功");
            } else {
                return ResultVO.fail("删除失败");
            }
        } catch (Exception e) {
            return ResultVO.fail("删除失败：" + e.getMessage());
        }
    }

    @Override
    public ResultVO<String> batchDelete(List<String> cameraIds) {
        try {
            UserDetail currentUser = UserContext.getUser();
            if (currentUser == null) {
                return ResultVO.fail("用户未登录");
            }

            if (CollectionUtils.isEmpty(cameraIds)) {
                return ResultVO.fail("请选择要删除的数据");
            }

            // 验证数据权限并逻辑删除
            LambdaQueryWrapper<CameraMonitoring> wrapper = new LambdaQueryWrapper<>();
            wrapper.in(CameraMonitoring::getCameraId, cameraIds);
            wrapper.eq(CameraMonitoring::getDelFlag, "0");

            List<CameraMonitoring> list = this.list(wrapper);
            if (list.isEmpty()) {
                return ResultVO.fail("未找到可删除的数据");
            }

            // 批量逻辑删除
            for (CameraMonitoring item : list) {
                item.setDelFlag("1");
                item.setUpdateBy(currentUser.getId());
                item.setUpdateTime(LocalDateTime.now());
            }

            boolean result = this.updateBatchById(list);
            if (result) {
                return ResultVO.ok("批量删除成功");
            } else {
                return ResultVO.fail("批量删除失败");
            }
        } catch (Exception e) {
            return ResultVO.fail("批量删除失败：" + e.getMessage());
        }
    }
}
